import React from 'react';
import { Button, Tabs } from 'antd';
import './index.less';
import SearchConfigModal from './components/search-config-modal';
import SearchComponent from './components/search-component';
import { getZoomeyeOrgList } from '@api/asset';
import AssetNetList from './components/asset-org-list';
import { actions as orgManageActions } from './reducer';
import lodash from 'lodash';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';

class AssetOrgManage extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      tab: 'notVerified', // 列表切换tab
      notVerifiedLoading: true, // 未在资产列表的loading
      notVerifiedData: [], // 未在资产列表数据
      notVerifiedPage: 1, // 未在资产列表页码
      notVerifiedPageSize: 10, // 未在资产列表每页数量
      notVerifiedCount: 0, // 未在资产列表总数
      notVerifiedSelectIds: [], // 未在资产列表已勾选的资产id集合
      isVerifiedLoading: true, // 已在资产列表的loading
      isVerifiedData: [], // 已在资产列表数据
      isVerifiedPage: 1, // 已在资产列表页码
      isVerifiedPageSize: 10, // 已在资产列表每页数量
      isVerifiedCount: 0, // 已在资产列表总数
      formValues: {}, // 搜索条件
      navBarStyle: {},
      isVerifiedSelectIds: [] // 已在资产列表已勾选的资产id集合
    };
  }

  componentDidMount() {
    this.getData('all'); //获取列表
    this.bindSocketIO(); //绑定socketIO
    this.props.initOrgManage();
    this.scrollContainer = document.querySelector('.asset-config-container');

    //内容页到顶部的距离减去header的距离就是需要浮动的距离
    this.offsetTop =
      document.querySelector('.content').offsetTop - document.querySelector('.header').clientHeight;
    this.scrollContainer.addEventListener('scroll', this.bindScroll);
  }

  bindScroll = e => {
    const height = e.target.scrollTop;
    //滚动时如果滚动区域短，可能出现样式塌陷导致的抖动
    if (height > this.offsetTop) {
      const { navBarStyle } = this.state;
      if (!Object.values(navBarStyle).length) {
        this.setState({
          navBarStyle: {
            position: 'fixed',
            zIndex: 999,
            backgroundColor: '#ffffff',
            width: '100%',
            top: '56px'
          }
        });
      }
    }
    if (height < this.offsetTop) {
      const { navBarStyle } = this.state;
      if (Object.values(navBarStyle).length) {
        this.setState({ navBarStyle: {} });
      }
    }
  };

  createFormRef = ref => {
    this['formRef'] = ref;
  };

  bindSocketIO = () => {
    const { socketIO, setIsUpdating } = this.props;
    if (!socketIO) {
      return;
    }
    socketIO.on('notice_handler', data => {
      //eslint-disabled-next-line
      const { updated_org: updatedOrg } = data;
      if (updatedOrg) {
        this.getData('all');
      }
      setIsUpdating(!updatedOrg);
    });
  };

  unbindSocketIO = () => {
    const { socketIO } = this.props;
    if (!socketIO) {
      return;
    }
    socketIO.cancel('updating_org');
  };

  componentWillUnmount() {
    this.unbindSocketIO();
    this.scrollContainer.removeEventListener('scroll', this.bindScroll);
  }

  /**
   * @param {string} type - 确定需要请求的type，all是全部请求，notVerified是未在资产列表，isVerified是已在资产列表
   *
   * */
  getData = type => {
    const {
      formValues,
      notVerifiedPage,
      notVerifiedPageSize,
      isVerifiedPage,
      isVerifiedPageSize
    } = this.state;

    if (this.scrollContainer) {
      this.scrollContainer.scrollTop = 0;
    }

    if (type === 'notVerified' || type === 'all') {
      this.setState({ notVerifiedLoading: true });
      const params = {
        page: type === 'all' ? 1 : notVerifiedPage,
        pageSize: notVerifiedPageSize,
        isVerified: false
      };
      if (Object.values(formValues).some(item => item)) {
        params.search = JSON.stringify(lodash.pickBy(formValues, item => item));
      }
      getZoomeyeOrgList(params)
        .then(res => {
          this.setState({
            notVerifiedData: lodash.get(res, 'data.data.list', []),
            notVerifiedCount: lodash.get(res, 'data.data.count', 0),
            notVerifiedPage: type === 'all' ? 1 : notVerifiedPage //点击搜索重置搜索
          });
        })
        .finally(() => {
          this.setState({ notVerifiedLoading: false });
        });
    }
    if (type === 'isVerified' || type === 'all') {
      this.setState({ isVerifiedLoading: true });

      const params = {
        page: type === 'all' ? 1 : isVerifiedPage,
        pageSize: isVerifiedPageSize,
        isVerified: true
      };
      if (Object.values(formValues).some(item => item)) {
        params.search = JSON.stringify(lodash.pickBy(formValues, item => item));
      }
      getZoomeyeOrgList(params)
        .then(res => {
          this.setState({
            isVerifiedData: lodash.get(res, 'data.data.list', []),
            isVerifiedCount: lodash.get(res, 'data.data.count', 0),
            isVerifiedPage: type === 'all' ? 1 : isVerifiedPage
          });
        })
        .finally(() => {
          this.setState({ isVerifiedLoading: false });
        });
    }
  };

  handlePageChange = (page, pageSize, type) => {
    if (type === 'isVerified') {
      this.setState({ isVerifiedPage: page, isVerifiedPageSize: pageSize }, () => {
        this.getData(type);
      });
    } else {
      this.setState({ notVerifiedPage: page, notVerifiedPageSize: pageSize }, () => {
        this.getData(type);
      });
    }
    this.scrollContainer.scrollTop = 0;
  };

  handleSearch = () => {
    const form = lodash.get(this, 'formRef.props.form', {});
    const formValues = form.getFieldsValue();
    this.setState({ formValues }, () => {
      this.getData('all');
    });
  };

  handleChangeSelectIds = (type, ids) => {
    this.setState({
      [`${type}SelectIds`]: ids
    });
  };

  render() {
    const {
      tab,
      notVerifiedData,
      notVerifiedPage,
      notVerifiedPageSize,
      notVerifiedCount,
      notVerifiedLoading,
      isVerifiedPage,
      isVerifiedPageSize,
      isVerifiedData,
      isVerifiedCount,
      isVerifiedLoading,
      navBarStyle,
      notVerifiedSelectIds,
      isVerifiedSelectIds
    } = this.state;
    const {
      openModal,
      updateImmediately,
      initError,
      searchConfigVisible,
      isUpdating,
      accountData
    } = this.props;
    const { apiKey } = accountData;
    const btnDisabled = isUpdating || !apiKey || initError;
    return (
      <div className="asset-org-manage">
        <div className="asset-org-manage-title">
          <span>公网资产查询</span>
          <Button type="link" onClick={openModal}>
            查询设置
          </Button>
          <Button type="link" onClick={() => updateImmediately(true)} disabled={btnDisabled}>
            {isUpdating ? '更新中' : '立即更新'}
          </Button>
        </div>
        <SearchComponent wrappedComponentRef={this.createFormRef} onSearch={this.handleSearch} />
        <div className="content">
          <Tabs activeKey={tab} onChange={tab => this.setState({ tab })} tabBarStyle={navBarStyle}>
            <Tabs.TabPane tab={`未在资产列表（${notVerifiedCount}条）`} key={'notVerified'}>
              <AssetNetList
                dataSource={notVerifiedData}
                onPageChange={this.handlePageChange}
                pageOpts={{
                  count: notVerifiedCount,
                  page: notVerifiedPage,
                  pageSize: notVerifiedPageSize
                }}
                errorOpts={{
                  initError,
                  searchError: !notVerifiedData.length
                }}
                type="notVerified"
                loading={notVerifiedLoading}
                handleVerifiedSuccess={() => this.getData('all')}
                selectIds={notVerifiedSelectIds}
                handleChangeSelectIds={this.handleChangeSelectIds}
                navBarStyle={navBarStyle}
              />
            </Tabs.TabPane>
            <Tabs.TabPane tab={`已在资产列表（${isVerifiedCount}条）`} key={'isVerified'}>
              <AssetNetList
                dataSource={isVerifiedData}
                onPageChange={this.handlePageChange}
                pageOpts={{
                  count: isVerifiedCount,
                  page: isVerifiedPage,
                  pageSize: isVerifiedPageSize
                }}
                errorOpts={{
                  initError,
                  searchError: !isVerifiedData.length
                }}
                type="isVerified"
                loading={isVerifiedLoading}
                handleVerifiedSuccess={() => this.getData('all')}
                selectIds={isVerifiedSelectIds}
                handleChangeSelectIds={this.handleChangeSelectIds}
                navBarStyle={navBarStyle}
              />
            </Tabs.TabPane>
          </Tabs>
        </div>
        {searchConfigVisible && <SearchConfigModal />}
      </div>
    );
  }
}

AssetOrgManage.propTypes = {
  history: PropTypes.object,
  isUpdating: PropTypes.bool,
  initError: PropTypes.bool,
  searchConfigVisible: PropTypes.bool,
  socketIO: PropTypes.object,
  openModal: PropTypes.func,
  updateImmediately: PropTypes.func,
  setIsUpdating: PropTypes.func,
  initOrgManage: PropTypes.func,
  accountData: PropTypes.object
};

const mapStateToProps = state => {
  return {
    isUpdating: lodash.get(state, 'orgManage.isUpdating', false),
    initError: lodash.get(state, 'orgManage.initError', false),
    searchConfigVisible: lodash.get(state, 'orgManage.searchConfigVisible', false),
    accountData: lodash.get(state, 'orgManage.accountData', {}),
    socketIO: lodash.get(state, 'socketIO.socketIO', null)
  };
};

const mapDispatchToProps = dispatch => {
  return {
    ...bindActionCreators(orgManageActions, dispatch)
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(AssetOrgManage);
